package cn.yyt.yytravel.chatMessage.service;


import cn.yyt.yytravel.chatList.mapper.ChatListMapper;
import cn.yyt.yytravel.chatList.pojo.ChatList;
import cn.yyt.yytravel.chatMessage.mapper.ChatMessageMapper;
import cn.yyt.yytravel.chatMessage.pojo.ChatMessage;
import cn.yyt.yytravel.chatMessage.pojo.dto.ChatMessageSaveParam;
import cn.yyt.yytravel.chatUserLink.mapper.ChatUserLinkMapper;
import cn.yyt.yytravel.chatUserLink.pojo.ChatUserLink;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ChatMessageServiceImpl implements ChatMessageService{

    @Autowired
    ChatMessageMapper chatMessageMapper;
    @Autowired
    ChatUserLinkMapper chatUserLinkMapper;
    @Autowired
    ChatListMapper chatListMapper;


    @Override
    public void saveChatMessage(ChatMessageSaveParam chatMessageSaveParam) {
        ChatMessage chatMessage = new ChatMessage();
        BeanUtils.copyProperties(chatMessageSaveParam,chatMessage);

        if(chatMessage.getLinkId() == null ){
            ChatUserLink chatUserLink = new ChatUserLink();
            BeanUtils.copyProperties(chatMessageSaveParam,chatUserLink);
            ChatList chatList = new ChatList();
            BeanUtils.copyProperties(chatUserLink,chatList);
            chatMessage.setSendTime(new Date());

            chatUserLink.setCreateTime(new Date());
            chatUserLinkMapper.insert(chatUserLink);//插入关系表

            chatList.setLinkId(chatUserLink.getLinkId());
            chatList.setReadStatus(0);
            chatListMapper.insert(chatList);//插入消息通知表

            chatMessage.setLinkId(chatList.getLinkId());
            chatMessage.setSendTime(new Date());
            chatMessageMapper.insert(chatMessage);//插入消息聊天框
        }else{
            chatMessage.setSendTime(new Date());
            ChatList chatList = new ChatList();
            chatList.setReadStatus(0);
            chatListMapper.update(chatList);//更新消息通知表
            chatMessageMapper.update(chatMessage);//更新消息详情页
        }

    }
}
